Package AccessControlDoorNode

Source Code of AccessControlDoorNode.AccessControlDoorNode

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package AccessControlDoorNode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import com.pi4j.device.piface.PiFace;
import com.pi4j.device.piface.PiFaceRelay;
import com.pi4j.device.piface.impl.PiFaceDevice;
import com.pi4j.io.gpio.PinState;
import com.pi4j.wiringpi.Spi;
import java.io.IOException;
import java.util.Arrays;

/**
*
* @author Stephen
*/
public class AccessControlDoorNode extends javax.swing.JFrame {

    /**
     * Creates new form AccessControlMonitorGUI
     */
    public AccessControlDoorNode() {
        initComponents();
        initilise();
    }

    // Define Variables
    Connection con = null;
    Statement st = null;
    PreparedStatement pst = null;
    ResultSet rs1 = null;
    ResultSet rs2 = null;
    ResultSet rs3 = null;
    ResultSet rsMonitor = null;
    boolean dbConnected = false;

    String doorId = null;
    boolean doorConfirmed = false;
    boolean doorLocked = false;

    PiFace piface;

    Timer checkDBTimer = new Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            monitorDBDoorOpen();
        }
    });

    Timer autoLockTimer = new Timer(5000, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            accessDoor();
        }
    });

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        dbUsernameTextField = new javax.swing.JTextField();
        dbConnectButton = new javax.swing.JButton();
        dbLocationTextField = new javax.swing.JTextField();
        dbPasswordField = new javax.swing.JPasswordField();
        connectionLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        doorIdTextField = new javax.swing.JTextField();
        cardIdTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        checkDoorIdButton = new javax.swing.JButton();

        jFrame1.setMinimumSize(new java.awt.Dimension(360, 185));

        jLabel5.setText("Username:");

        jLabel1.setText("Location:");

        jLabel6.setText("Password:");

        dbUsernameTextField.setText("admin");

        dbConnectButton.setText("Connect");
        dbConnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbConnectButtonActionPerformed(evt);
            }
        });

        dbLocationTextField.setText("jdbc:mysql://192.168.1.92:3306/pidoor");

        dbPasswordField.setText("password");

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jFrame1Layout.createSequentialGroup()
                        .addGap(128, 128, 128)
                        .addComponent(dbConnectButton))
                    .addGroup(jFrame1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(dbUsernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
                            .addComponent(dbLocationTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
                            .addComponent(dbPasswordField))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(dbLocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbUsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(dbPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dbConnectButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        connectionLabel.setText("No Connection");

        jButton1.setText("Set Connection");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Door ID:");

        cardIdTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cardIdTextFieldActionPerformed(evt);
            }
        });

        jLabel3.setText("Card Entry:");

        checkDoorIdButton.setText("Check");
        checkDoorIdButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkDoorIdButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(connectionLabel)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cardIdTextField)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(doorIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(checkDoorIdButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connectionLabel)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(doorIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(checkDoorIdButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cardIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void initilise() {
        doorIdTextField.setEnabled(false);
        checkDoorIdButton.setEnabled(false);
        cardIdTextField.setEnabled(false);

        try {
            piface = new PiFaceDevice(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create Pi Face Device", e);
        }

    }

    private void dbConnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbConnectButtonActionPerformed
        String dbLocation = dbLocationTextField.getText();
        String dbUsername = dbUsernameTextField.getText();
        char[] dbPassword = dbPasswordField.getPassword();
        String dbStringPassword = new String(dbPassword);
       
        //Zero out the possible password, for security.
        Arrays.fill(dbPassword, '0');

        // Tries to connect to the database
        try {

            con = DriverManager.getConnection(dbLocation, dbUsername, dbStringPassword);
           
            // clear password string
            dbStringPassword = "0";
           
            JOptionPane.showMessageDialog(this, "Database connection successful.");
            connectionLabel.setText("Connected");
            dbConnected = true;
            jFrame1.setVisible(false);
            doorIdTextField.setEnabled(true);
            checkDoorIdButton.setEnabled(true);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Database connection failed: \n" + ex.getMessage());
            connectionLabel.setText("No Connection");
            dbConnected = false;
            doorIdTextField.setEnabled(false);
            checkDoorIdButton.setEnabled(false);
        }

        // Note the password field shouldn't be entered as a text field, this is insecure
        // For further details see the following link:
        // http://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html
    }//GEN-LAST:event_dbConnectButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        jFrame1.setVisible(true);
        jFrame1.toFront();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void checkDoorIdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkDoorIdButtonActionPerformed
        doorId = doorIdTextField.getText();
        // We must now check if this door exists
        try {
            pst = con.prepareStatement("SELECT COUNT(*) FROM Door WHERE dId = (?)");
            pst.setString(1, doorId); // Door Id
            rs1 = pst.executeQuery();

            while (rs1.next()) {
                if ((rs1.getInt(1)) == 1) {
                    JOptionPane.showMessageDialog(this, "Door confirmed.");
                    doorConfirmed = true;
                    cardIdTextField.setEnabled(true);

                } else {
                    JOptionPane.showMessageDialog(this, "This door does not exist, please enter the ID of a door in the database:");
                    cardIdTextField.setEnabled(false);
                }
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (rs1 != null) {
                    rs1.close();
                }
                if (con != null) {
                    //con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }

        if (doorConfirmed == true) {

            checkDBTimer.setInitialDelay(0);
            checkDBTimer.start();
        }

    }//GEN-LAST:event_checkDoorIdButtonActionPerformed

    private void monitorDBDoorOpen() {
        try {
            pst = con.prepareStatement("SELECT * FROM Door WHERE dId = (?)");
            pst.setString(1, doorId); // Door Id
            rsMonitor = pst.executeQuery();

            while (rsMonitor.next()) {
                if ((rsMonitor.getBoolean(3)) == true) {
                    // The door is locked

                    piface.getRelay(PiFaceRelay.K0).close();
                    if (doorLocked == false) {
                        //JOptionPane.showMessageDialog(this, "Door Locked from DB");
                    }
                    doorLocked = true;

                } else {
                    // The door is unlocked

                    piface.getRelay(PiFaceRelay.K0).open();
                    if (doorLocked == true) {
                        //JOptionPane.showMessageDialog(this, "Door unlocked from DB");
                    }
                    doorLocked = false;

                }
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (rsMonitor != null) {
                    rsMonitor.close();
                }
                if (con != null) {
                    //con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        // Check if the door is open/closed and update the database
        try {
            if (piface.getInputPin(0).isHigh()) {
                pst = con.prepareStatement("UPDATE Door SET dOpenState = false WHERE dId = (?)");
            } else if (piface.getInputPin(0).isLow()){
                pst = con.prepareStatement("UPDATE Door SET dOpenState = true WHERE dId = (?)");
            }
        
            pst.setString(1, doorId); // Door Id
            pst.execute();

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    //con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }

    }

    private void cardIdTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cardIdTextFieldActionPerformed
        try {
            pst = con.prepareStatement("SELECT * FROM Person WHERE pCardNo = (?)");
            pst.setString(1, cardIdTextField.getText()); // Card Number
            rs1 = pst.executeQuery(); // Returns a person

            int personReturned = 0;
            int personGroupReturned = 0;
            int doorGroupReturned = 0;

            while (rs1.next()) {
                personReturned++;

                // Are they in an access group               
                pst = con.prepareStatement("SELECT * FROM PersonGroup WHERE pId = (?)");
                pst.setInt(1, rs1.getInt(1)); // Person Id
                rs2 = pst.executeQuery(); // Returns a person group

                while (rs2.next()) {
                    personGroupReturned++;

                    // Check if this person group corisponds to a door group
                    pst = con.prepareStatement("SELECT * FROM DoorGroup WHERE agId = (?)");
                    pst.setInt(1, rs2.getInt(3)); // Access Group ID
                    rs3 = pst.executeQuery(); // Returns a door group

                    while (rs3.next()) {
                        doorGroupReturned++;

                        // Check if this door group contains the correct door
                        if (Integer.toString(rs3.getInt(2)).equals(doorId)) {
                            // This person has permission to access this door
//                            JOptionPane.showMessageDialog(this, "Success!");

                            piface.getRelay(PiFaceRelay.K0).open();
                            checkDBTimer.stop();

                            autoLockTimer.setInitialDelay(5000);
                            autoLockTimer.setRepeats(false);
                            autoLockTimer.start();

                            cardIdTextField.setText("");
                        }
                    }
                }
            }

            if (personReturned == 0) {
                //JOptionPane.showMessageDialog(this, "This card does not exist.");
                cardIdTextField.setText("");
            }

            if (personReturned > 0 && personGroupReturned == 0) {
                //JOptionPane.showMessageDialog(this, "This card number does not exist in a group.");
                cardIdTextField.setText("");
            }
            if (personReturned > 0 && personGroupReturned > 0 && doorGroupReturned == 0) {
                //JOptionPane.showMessageDialog(this, "This person group does not corispond with a door group.");
                cardIdTextField.setText("");
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (rs1 != null) {
                    rs1.close();
                }
                if (con != null) {
                    //con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(AccessControlDoorNode.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    }//GEN-LAST:event_cardIdTextFieldActionPerformed

    public void accessDoor() {
        //JOptionPane.showMessageDialog(this, "close...");
        piface.getRelay(PiFaceRelay.K0).close();
        checkDBTimer.start();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AccessControlDoorNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AccessControlDoorNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AccessControlDoorNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AccessControlDoorNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AccessControlDoorNode().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField cardIdTextField;
    private javax.swing.JButton checkDoorIdButton;
    private javax.swing.JLabel connectionLabel;
    private javax.swing.JButton dbConnectButton;
    private javax.swing.JTextField dbLocationTextField;
    private javax.swing.JPasswordField dbPasswordField;
    private javax.swing.JTextField dbUsernameTextField;
    private javax.swing.JTextField doorIdTextField;
    private javax.swing.JButton jButton1;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    // End of variables declaration//GEN-END:variables
}
TOP

Related Classes of AccessControlDoorNode.AccessControlDoorNode

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.